package com.liuzy.dsoframer.util;

import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class DiskFileUtil {
    private static final Object lock = new Object();

    // 列出所有文件
    public static List<DiskFile> list(File dir) {
        synchronized (lock) {
            List<DiskFile> diskFiles = new ArrayList<>();
            File[] files = dir.listFiles();
            if (files != null) {
                for (File file : files) {
                    DiskFile diskFile = new DiskFile();
                    diskFile.setMd5(fileMd5(file));
                    diskFile.setName(file.getName());
                    diskFile.setAuthor("交通银行");
                    diskFile.setMtime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(file.lastModified()));
                    diskFiles.add(diskFile);
                }
            }
            return diskFiles;
        }
    }

    // 查找一个文件
    public static File find(File dir, String id) {
        synchronized (lock) {
            File[] files = dir.listFiles();
            if (files != null) {
                for (File file : files) {
                    String md5 = fileMd5(file);
                    if (md5.equals(id)) {
                        return file;
                    }
                }
            }
            return null;
        }
    }

    // 删除一个文件
    public static void delete(File dir, String id) {
        synchronized (lock) {
            File file = find(dir, id);
            if (file != null) {
                if (!file.delete()) {
                    file.deleteOnExit();
                }
            }
        }

    }

    // 保存一个文件
    public static String save(File dir, String id, MultipartFile multipartFile) {
        synchronized (lock) {
            try {
                File src = find(dir, id);
                File dst;
                String date = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
                if (src == null) {
                    dst = new File(dir, date + ".doc");
                } else {
                    String name = src.getName();
                    String suffix = name.substring(name.lastIndexOf("."));
                    name = name.substring(0, name.length() - suffix.length());
                    dst = new File(dir, name + "_" + date + suffix);
                }
                multipartFile.transferTo(dst);
                return fileMd5(dst);
            } catch (Exception e) {
                e.printStackTrace();
                return "ERR";
            }
        }
    }

    /* ################################# */

    private static final char[] hexCode = "0123456789ABCDEF".toCharArray();

    public static String fileMd5(File file) {
        try (FileInputStream stream = new FileInputStream(file)) {
            MessageDigest digest = MessageDigest.getInstance("MD5");
            byte[] buf = new byte[8192];
            int len;
            while ((len = stream.read(buf)) > 0) {
                digest.update(buf, 0, len);
            }
            return toHexString(digest.digest());
        } catch (IOException | NoSuchAlgorithmException e) {
            e.printStackTrace();
            return "";
        }
    }

    public static String toHexString(byte[] data) {
        StringBuilder r = new StringBuilder(data.length * 2);
        for (byte b : data) {
            r.append(hexCode[(b >> 4) & 0xF]);
            r.append(hexCode[(b & 0xF)]);
        }
        return r.toString();
    }
}
